<!-- OAuthCallback.vue -->
<template>
  <div class="callback-container">
    <div v-if="loading" class="loading">
      <p>正在处理登录...</p>
    </div>
    <div v-else-if="error" class="error">
      <p>登录失败：{{ error }}</p>
      <button @click="goHome">返回首页</button>
    </div>
    <div v-else class="success">
      <p>登录成功！正在跳转...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const loading = ref(true)
const error = ref('')

// const API_URL = 'http://localhost:9000'
const API_URL = 'https://api.tiffanylamps.com.cn'

onMounted(async () => {
  await handleCallback()
})

const handleCallback = async () => {
  try {
    const urlParams = new URLSearchParams(window.location.search)
    const code = urlParams.get('code')
    const errorParam = urlParams.get('error')
    
    if (errorParam) {
      error.value = errorParam
      loading.value = false
      return
    }
    
    if (!code) {
      error.value = '未获取到授权码'
      loading.value = false
      return
    }
    
    // 发送授权码到后端
    const response = await axios.post(`${API_URL}/auth/google/callback`, { code })
    
    if (response.data.success) {
      const { token, user } = response.data
      
      // 保存token
      localStorage.setItem('authToken', token)
      localStorage.setItem('user', JSON.stringify(user))
      
      // 跳转到主页或指定页面
      router.push('/')
    } else {
      error.value = '登录处理失败'
    }
    
  } catch (err) {
    console.error('OAuth callback error:', err)
    error.value = '网络错误，请重试'
  } finally {
    loading.value = false
  }
}

const goHome = () => {
  router.push('/')
}
</script>

<style scoped>
.callback-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  text-align: center;
}

.loading, .error, .success {
  padding: 20px;
  border-radius: 8px;
  max-width: 400px;
}

.loading {
  background-color: #f0f0f0;
}

.error {
  background-color: #ffe6e6;
  color: #d00;
}

.success {
  background-color: #e6ffe6;
  color: #080;
}

button {
  margin-top: 15px;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}
</style>